package com.cvtt.common;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

public class Util {
	public static final String CONFIG_MSG_SOUND = "setting_msg_sound";// 新消息提示音
	public static final String CONFIG_DIAL_VIBRATE = "setting_dial_vibrate";// 拨号按键震动
	public static final String CONFIG_DIAL_SOUND = "setting_dial_sound";// 拨号按键声音
	public static final String CONFIG_CALL_OK_VIBRATE = "setting_connect_vibrate";// 接通震动
	public static final String CONFIG_CALL_NETWORK_WARNING = "setting_network_warning";// 每次呼叫提示
	private static final SharedPreferences sharedPreferences = null;
	

	/**
	 * 根据传入的时间，格式化成 2013-12-14 16：00 ,
	 * 
	 * @param milliseconds
	 * @return
	 */
	public static String formatterDateAndTime(long milliseconds) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(milliseconds);
		int hour = calendar.get(Calendar.HOUR_OF_DAY);
		int minute = calendar.get(Calendar.MINUTE);
		String date = formatterDate(milliseconds, "-");
		StringBuilder str = new StringBuilder();
		str.append(date + " ");
		if (hour < 10) {
			str.append(" ");// 不补0位，补个空格对齐
		}
		str.append(hour);
		str.append(":");
		if (minute < 10) {
			str.append(0);// 添0补位
		}
		str.append(minute);

		return str.toString();
	}
	
	/**
	 * 通过milliseconds得到一个格式为"yyyy-mm-dd"的日期，比如2009-10-29
	 */
	public static String formatterDate(long milliseconds, String separator) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(milliseconds);
		int month = calendar.get(Calendar.MONTH) + 1;
		int day = calendar.get(Calendar.DAY_OF_MONTH);
		StringBuilder str = new StringBuilder();
		str.append(calendar.get(Calendar.YEAR));
		str.append(separator);
		str.append(month);// 月份从0开始
		str.append(separator);
		str.append(day);
		return str.toString();
	}
	
	public static void sendSystemMsg(Context context, String number, String content) {
		Uri smsToUri = Uri.parse("smsto:" + number);
		Intent mIntent = new Intent(android.content.Intent.ACTION_SENDTO, smsToUri);
		mIntent.putExtra("sms_body", content);
		try {
			context.startActivity(mIntent);
		}
		catch (Exception e) {
		}
	}

	public static String filterUnNumber(String str) {
		String regEx = "[^0-9]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.replaceAll("").trim();
	}

	public static boolean isIPAddress(String str) {
		Pattern pattern = Pattern.compile("[0-9.]+");
		return pattern.matcher(str).matches();
	}

	public static boolean isLetter(String str) {
		if ((str == null) || (str.length() < 1))
			return false;
		for (int i = 0; i < str.length(); i++) {
			int chr = str.charAt(i);
			if ((chr < 'A' || chr > 'Z') && (chr < 'a' || chr > 'z'))
				return false;
		}
		return true;
		// Pattern pattern = Pattern.compile("[a-zA-Z]+");
		// return pattern.matcher(str).matches();
	}

	public static boolean isNumeric(String str) {
		// if((str == null) || (str.length() < 1))
		// return false;
		// Pattern pattern = Pattern.compile("[0-9]+");
		// return pattern.matcher(str).matches();
		if ((str == null) || (str.length() < 1))
			return false;
		for (int i = str.length(); --i >= 0;) {
			int chr = str.charAt(i);
			if (chr < 48 || chr > 57)
				return false;
		}
		return true;
	}

	public static boolean isNumeric2(String str) {
		for (int i = str.length(); --i >= 0;) {
			if (!Character.isDigit(str.charAt(i))) {
				return false;
			}
		}
		return true;
	}

	public static boolean isNumeric3(String str) {
		for (int i = str.length(); --i >= 0;) {
			int chr = str.charAt(i);
			if (chr < 48 || chr > 57)
				return false;
		}
		return true;
	}

	public static String toUTF8String(InputStream is) throws IOException {
		StringBuffer sb = new StringBuffer();

		InputStreamReader isReader = new InputStreamReader(is, "UTF-8");

		BufferedReader br = new BufferedReader(isReader);
		String data = "";

		while ((data = br.readLine()) != null) {
			sb.append(data);
		}

		return sb.toString();
	}

	public static String makeUUID() {
		String uuid = UUID.randomUUID().toString();
		uuid = uuid.replace("-", "");
		return uuid.toLowerCase();
	}

	// dip to pix
	public static int DipToPixels(Context context, int dip) {
		final float SCALE = context.getResources().getDisplayMetrics().density;

		float valueDips = dip;
		int valuePixels = (int) (valueDips * SCALE + 0.5f);

		return valuePixels;
	}

	// pix to dip
	public static float PixelsToDip(Context context, int Pixels) {
		final float SCALE = context.getResources().getDisplayMetrics().density;

		float dips = Pixels / SCALE;

		return dips;
	}

	public static void beginEdit(Activity act, EditText et) {
		et.requestFocus();
		InputMethodManager iM = (InputMethodManager) act.getSystemService(Context.INPUT_METHOD_SERVICE);
		iM.showSoftInput(et, 0);
	}

	public static void hideKeyboard(Activity act, View v) {
		InputMethodManager iM = (InputMethodManager) act.getSystemService(Context.INPUT_METHOD_SERVICE);

		iM.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
	}

	public static String formatTime(long ms) {
		// long now=System.currentTimeMillis();
		Date date = new Date(ms);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateStr = sdf.format(date);
		return dateStr;
	}

	public static String adjustNumber(String number) {
		String newNumber = new String(number);
		if (newNumber.startsWith("86") && (newNumber.length() == 13)) {
			newNumber = newNumber.substring(2);
		}

		if (!newNumber.startsWith("0")) {
			if (newNumber.startsWith("1") && (newNumber.length() == 11)) {
				newNumber = "0" + newNumber;
			}
		}

		return newNumber;
	}

	public static String byteArrayToHexString(byte[] byteArray) {
		StringBuffer resultSb = new StringBuffer();

		for (int i = 0; i < byteArray.length; i++) {
			String hexStr = Integer.toHexString(0xFF & byteArray[i]);
			if (hexStr.length() == 1)
				resultSb.append("0").append(hexStr);
			else
				resultSb.append(hexStr);
		}

		return resultSb.toString();
	}

	

	public static boolean checkNetwork2(Context ctx) {
		ConnectivityManager manager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkinfo = manager.getActiveNetworkInfo();

		if (networkinfo == null || !networkinfo.isAvailable()) {
			return false;
		}
		return true;
	}

	public static <T> void quickSort(List<T> list, Comparator<? super T> comparator) {
		if ((list == null) || (list.size() < 2))
			return;
		quickSort(list, 0, list.size() - 1, comparator);
	}

	public static <T> void quickSort(List<T> list, int begin, int end, Comparator<? super T> comparator) {
		if (begin < end) {
			int p = partition(list, begin, end, comparator);
			quickSort(list, begin, p - 1, comparator);
			quickSort(list, p + 1, end, comparator);
		}
	}

	public static <T> int partition(List<T> list, int begin, int end, Comparator<? super T> comparator) {
		int p = begin - 1;
		T eEnd = list.get(end);
		for (int j = begin; j < end; j++) {
			T eJ = list.get(j);
			if (comparator.compare(eJ, eEnd) <= 0) {
				p++;
				T eP = list.get(p);
				list.set(p, eJ);
				list.set(j, eP);
			}
		}
		p++;
		T eP = list.get(p);
		list.set(p, eEnd);
		list.set(end, eP);
		return p;
	}

	public static String getDevID(Context ctx) {
		TelephonyManager phoneMgr = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
		String devId = phoneMgr.getDeviceId();
		if (devId == null) {
			devId = "null";
		}
		return devId;
	}

	public static String getDevInfo(Context ctx) {
		StringBuffer sb = new StringBuffer();

		sb.append(android.os.Build.MODEL);
		sb.append(" ");
		sb.append("Android V");
		sb.append(android.os.Build.VERSION.RELEASE);
		sb.append("*");

		TelephonyManager phoneMgr = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
		String devId = phoneMgr.getDeviceId();
		if (devId == null) {
			devId = "null";
		}

		sb.append(devId);

		return sb.toString();
	}

	public static String getLocalIpAddress() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		}
		catch (SocketException ex) {
		}
		return "127.0.0.1";
	}

	// Added by huah in 2012-08-25
	public static byte[] InputStreamToByte(InputStream is) throws IOException {
		ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
		int ch;
		while ((ch = is.read()) != -1) {
			bytestream.write(ch);
		}
		byte outdata[] = bytestream.toByteArray();
		bytestream.close();
		return outdata;
	}

	// Modified by huah in 2013-06-27
	public static int getAvailablePort(int min_port) {

		DatagramSocket s = null;
		int port_range = 65535 - min_port;
		if(port_range <= 0)
			port_range = 10;
		int port = min_port; 
		for (int i = 0; i < port_range; i++) 
		{
			try 
			{
				port = min_port + com.zoolu.tools.Random.nextInt(port_range);
				s = new DatagramSocket(port, InetAddress.getLocalHost());
				s.close();
				break;
			} 
			catch (Exception e) 
			{
				e.printStackTrace();
				continue;
			}
			catch(Error e)
			{
				e.printStackTrace();
				continue;
			}
		}
		
		return port;
	}
	

	public static String getUNumber(String xmppUri) {
		if (TextUtils.isEmpty(xmppUri))
			return null;
		String uNumber = xmppUri;
		int index = xmppUri.indexOf("@");
		if (index > 0) {
			uNumber = xmppUri.substring(0, index);
		}
		return uNumber;
	}

	public static String getStartString(String str, String sep) {
		if (TextUtils.isEmpty(str))
			return null;
		String subStr = str;
		int index = str.indexOf(sep);
		if (index > 0) {
			subStr = str.substring(0, index);
		}
		return subStr;
	}

	public static boolean matchPhoneNumber(String number1, String number2) {
		if (TextUtils.isEmpty(number1) || TextUtils.isEmpty(number2))
			return false;
		// if(!Util.isNumeric(number1) || !Util.isNumeric(number2))
		// return false;
		if (TextUtils.equals(number1, number2) || TextUtils.equals(number1, "86" + number2) || TextUtils.equals("86" + number1, number2))
			return true;
		return false;
	}

	// Added by huah in 2012-10-09
	public static String getValidPhone(String phone) {
		if (TextUtils.isEmpty(phone))
			return null;
		String validNumber = phone;
		if (validNumber.startsWith("86") && (validNumber.length() == 13)) {
			validNumber = validNumber.substring(2);
		}
		return validNumber;
	}
	
	public static int strToInt(String str) {
		int value;
		try {
			value = Integer.parseInt(str.trim());
		}
		catch (NumberFormatException e) {
			// ULogger.printErrorMessage(e);
			value = -1;
		}
		return value;
	}

	/**
	 * 根据传的毫秒数转为日期, 返回日期格式yyyy-MM-DD
	 * 
	 * @param time
	 * @return
	 */
	public static String formatDate(long milliseconds) {
		if (milliseconds <= 0)
			return "";
		Date date = new Date(milliseconds);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String strDate = format.format(date);
		return strDate;
	}

	public static long strToLong(String str) {
		long value;
		try {
			value = Long.valueOf(str);
		}
		catch (NumberFormatException e) {
			// ULogger.printErrorMessage(e);
			value = -1;
		}
		return value;
	}

	/**
	 * 判断手机是否是小米系统
	 * 
	 * @return
	 */
	public static boolean isMIUI() {
		Properties pp = System.getProperties();
		String sys = pp.getProperty("http.agent", "");
		if (sys.contains("MIUI")) {
			return true;
		}
		return false;
	}

	/**
	 * 判断是否是GT19228
	 * 
	 * @return
	 */
	public static boolean isGT19228() {
		try {
			String model = android.os.Build.MODEL;
			String brand = android.os.Build.BRAND;
			if ("GT-I9228".equals(model) && "samsung".equals(brand)) {
				return true;
			}
			return false;
		}
		catch (Exception e) {
			return false;
		}
		catch (Error e) {
			return false;
		}
	}
	
	public static String getMac(Context ctx) {
		try {
			WifiManager wifi = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
			WifiInfo info = wifi.getConnectionInfo();
			String mac=info.getMacAddress();
			if(TextUtils.isEmpty(mac))
				return "null";
			return mac;
		}
		catch (Exception e) {
			return "null";
		}catch (Error e) {
			return "null";
		}

	}

	public static String getIP() {
		String ipAddress = "127.0.0.1";
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						ipAddress = inetAddress.getHostAddress().toString();
					}
				}
			}
		}
		catch (SocketException ex) {
		}
		catch (Exception e) {
		}
		catch (Error e) {
		}

		if (!isIPAddress(ipAddress)) {
			ipAddress = "127.0.0.1";
		}
		return ipAddress;
	}


	public static String getClientInfo() {
		
		//appVersionInfo = appVersionInfo + appVersionName + "." + channel;
		
		StringBuffer infoSb = new StringBuffer();
		String model = android.os.Build.MODEL;
		// add by xiaofei 2014-7-2
		if (!TextUtils.isEmpty(model) && model.contains("*")) {
			model = model.replace("*", "");
		}
		String release = android.os.Build.VERSION.RELEASE;
		if (!TextUtils.isEmpty(release) && release.contains("*")) {
			release = release.replace("*", "");
		}
		if(TextUtils.isEmpty(model))
			model="";
		if(TextUtils.isEmpty(release))
			release="";
		infoSb.append(model);
		infoSb.append(" ");
		infoSb.append("Android V");
		infoSb.append(release);
		return infoSb.toString();
	}

	public static String getIMEI(Context ctx) {
		String devId = "";
		try {
			TelephonyManager phoneMgr = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
			devId = phoneMgr.getDeviceId();
			if (TextUtils.isEmpty(devId)) {
				devId = "null";
			}
		}
		catch (Exception e) {
			devId = "null";
		}
		catch (Error e) {
			devId = "null";
		}
		return devId;
	}
	
	

	// =======================有关时间的方法========================================
	/**
	 * 通过milliseconds得到一个格式为"yyyymmddhhmmssmm"的日期，比如20120521165730520
	 */
	public static String getTimeSuffix(long milliseconds) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(milliseconds);
		StringBuilder str = new StringBuilder();
		int time;
		str.append(calendar.get(Calendar.YEAR));
		if ((time = calendar.get(Calendar.MONTH) + 1) < 10) {
			str.append(0);
		}
		str.append(time);
		if ((time = calendar.get(Calendar.DAY_OF_MONTH)) < 10) {
			str.append(0);
		}
		str.append(time);
		if ((time = calendar.get(Calendar.HOUR_OF_DAY)) < 10) {
			str.append(0);
		}
		str.append(time);
		if ((time = calendar.get(Calendar.MINUTE)) < 10) {
			str.append(0);
		}
		str.append(time);
		if ((time = calendar.get(Calendar.SECOND)) < 10) {
			str.append(0);
		}
		str.append(time);
		if ((time = calendar.get(Calendar.MILLISECOND)) < 10) {
			str.append("00");
		}
		else if (time < 100) {
			str.append("0");
		}
		str.append(time);
		return str.toString();
	}
	
	/**
	 * 将接收到的音频文件写入sd卡
	 * 
	 * @param data
	 * @param fileName
	 * @throws IOException
	 */
	public static File writeAudioToFile(byte[] data, String fileName) {
		File file = null;
		try {
			file = new File(getAudioDir(), fileName + ".vphone");
			FileOutputStream outStream = new FileOutputStream(file);
			outStream.write(data);
			outStream.close();
		}
		catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return file;
	}

	/**
	 * 创建新的音频文件夹
	 * 
	 * @return
	 */
	public static File getAudioDir() {
		File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/voip/voice/");
		if (!file.exists()) {
			file.mkdirs();
		}
		return file;
	}
	
	public static boolean getBoolean(String key, boolean defaultValue) {
		return getBoolean(key, defaultValue);
	}
	
	private static SharedPreferences getSharedPreferences(String text, int modePrivate) {
		SharedPreferences sp = getSharedPreferences(text,Context.MODE_PRIVATE);
		return sp;
	}
	
	// 接通震动
	public static void setCallOKVibrate(boolean enable) {
		putBoolean(CONFIG_CALL_OK_VIBRATE, enable);
	}

	public static boolean getCallOKVibrate() {
		return getBoolean(CONFIG_CALL_OK_VIBRATE, false);
	}
	
	public static void putBoolean(String key, boolean value) {
		Editor editor = getSharedPreferences("VIBRATE",Context.MODE_PRIVATE).edit();
		editor.putBoolean(key, value);
		editor.commit();
	}
	
	
}
